﻿using System.Collections.Generic;

namespace org.xisoft.game.utils.game.algorithms
{
    public abstract class AlphaBetaAlgorithm<Broad> : AiAlgorithm<Broad>
                 where Broad : ChessBoardBase
    {
        private readonly long MATE = long.MaxValue / 2;
        public override MoveAction Search(Broad broad, int depth)
        {

            return Search(broad,  depth, -MATE, MATE);
        }

        public MoveAction Search(Broad broad,  int depth, long alpha, long beta)
        {
            List<MoveAction> movies = GetSortedAllCanMoves(broad);
            return Search(broad, movies, depth, alpha, beta);
        }

        public virtual MoveAction Search(Broad broad, List<MoveAction> movies, int depth, long alpha, long beta)
        {

            MoveAction bestMove = null;

            if ((depth <= 0 && movies.Count > 0))
                return movies[0];


            foreach (MoveAction move in movies)
            {

                broad.DoNextMove(move);
                ResumeThinking();
                List<MoveAction> anotherMovies = GetSortedAllCanMoves(broad);
                MoveAction action = Search(broad, anotherMovies,  depth - 1, -beta, -alpha);
                broad.Undo();

                if (action != null)
                    move.Score -= action.Score;


                if (bestMove == null || bestMove.Score < move.Score)
                {
                    bestMove = move;
                    bestMove.Next = action;
                    alpha = bestMove.Score;

                    if (bestMove.Score >= beta)
                    {
                        break;
                    }
                }

            }


            return bestMove;
        }
    }
}
